package com.mfs.common.utills;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Channel 工具类
 * @author mfs
 * @date
 * */
public class ChannelUtil {
    public static void write(SocketChannel channel, String msg) {

    }

    public static byte[] read(SocketChannel channel) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(8 * 1024);
        byte[] bytes = new byte[0];
        int length = 0;
        while ((length = channel.read(byteBuffer)) > 0) {
            byte[] byteCopy = new byte[bytes.length + length];
            System.arraycopy(bytes, 0, byteCopy, 0, bytes.length);
            byteBuffer.flip();
            byteBuffer.get(byteCopy, bytes.length, length);
            byteBuffer.clear();
            bytes = byteCopy;
        }
        if (length == -1) {
            throw new  IOException("连接关闭");
        }
        return bytes;
    }


    /**
     * 关闭所有通道，忽略异常
     * */
    public static void closeSocketChannel(SocketChannel ...socketChannels) {
        for (SocketChannel channel : socketChannels) {
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
